<template>
	<view class="Applyappointment">
		<view class="hdsIGN">
			<h3>就诊人信息</h3>
		</view>
		<view style="height: 84vh;overflow-y: auto;">
			<uni-forms ref="form" :modelValue="formData" label-position="alignment" labelWidth="90px" :rules="rules">
				<uni-forms-item required label="就诊人姓名" name="patientName" :disabled="true">
					<uni-easyinput type="text" v-model="formData.patientName" placeholder="请输入就诊人姓名"
						:disabled='disabled' />
				</uni-forms-item>
				<uni-forms-item required label="证件类型" name="idType">
					<uni-data-select v-model="formData.idType" :localdata="IDType" :arrayConfig="configParams"
						:disabled='disabled'></uni-data-select>
				</uni-forms-item>
				<uni-forms-item required label="证件号码" name="idNumber" :disabled="true">
					<uni-easyinput type="text" v-model="formData.idNumber" placeholder="请输入证件号码" :disabled='disabled' />
				</uni-forms-item>
				<uni-forms-item required label="手机号" name="contactNumber">
					<uni-easyinput type="text" v-model="formData.contactNumber" placeholder="请输入手机号"
						:disabled='disabled' />
				</uni-forms-item>
				<uni-forms-item required label="备用电话" name="backupNumber">
					<uni-easyinput type="text" v-model="formData.backupNumber" placeholder="请输入备用电话"
						:disabled='disabled' />
				</uni-forms-item>
				<uni-forms-item required label="医保卡号" name="insuranceCardNumber">
					<uni-easyinput type="text" v-model="formData.insuranceCardNumber" placeholder="请输入医保卡号"
						:disabled='disabled' />
				</uni-forms-item>
				<uni-forms-item label="异地就诊" required>
					<uni-data-checkbox v-model="formData.outOfTown" :localdata="medicalTreatment"
						:disabled='disabled' />
				</uni-forms-item>
				<view class="hdsIGN">
					<h3>医院信息</h3>
				</view>
				<uni-forms-item label="医院城市" name="hospitalCity">
					<uni-data-picker placeholder="请选择" popup-title="请选择所在地区" :localdata="dataTree"
						v-model="formData.hospitalCity" @change="onchange" @nodeclick="onnodeclick"
						@popupopened="onpopupopened" @popupclosed="onpopupclosed" :readonly='disabled'>
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="医院名称" name="hospitalTree">
					<uni-data-picker placeholder="请选择" popup-title="请选择医院名称" :localdata="hospitalTree"
						v-model="formData.hospitalName" @change="onchange" @nodeclick="onnodeclick1"
						@popupopened="onpopupopened" @popupclosed="onpopupclosed" :readonly='disabled'>
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item required label="科室名称" name="departmentName">
					<uni-easyinput type="text" v-model="formData.departmentName" placeholder="请输入科室名称"
						:disabled='disabled' />
				</uni-forms-item>
				<uni-forms-item label="预期时间" name="expectedTime">
					<uni-datetime-picker v-model="formData.expectedTime" type="daterange" @maskClick="maskClick"
						:disabled='disabled' />
				</uni-forms-item>
				<view class="hdsIGN" style="display: flex;justify-content: space-between; align-items: center;"
					v-if="currentItem.title == '住院安排'">
					<h3>住院单</h3>
					<h5 style="color: dodgerblue;">查看重大疾病目录</h5>
				</view>
				<!-- <uni-forms-item label="" name="expectedTime"> -->
				<uni-file-picker v-if="currentItem.title == '住院安排'" v-model="imageValue" fileMediatype="image"
					mode="grid" @select="select" @progress="progress" @success="success" @fail="fail" />
				<!-- </uni-forms-item> -->
			</uni-forms>
		</view>
		<view style="position: absolute;bottom: 0rpx;left: 0rpx;width: 100%;background: #fff;" v-if="!disabled">
			<button style="margin: 20rpx;" class="plainlk1" @click="sendBtnautograph">提交预约</button>
		</view>
		<uni-popup ref="messages" type="dialog">
			<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确定" title="申请成功" @confirm="dialogConfirm2"
				@close="dialogClose2">
				<view class="tanchuang" style="text-indent: 24px;letter-spacing: 1px;">
					申请成功！当前权益使用次数剩余{{this.shengyu}}次
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import { getToken } from '@/utils/auth'
	import {
		document_type,
		Beneficiaries,
		EditActivationCodes,
		provincelist,
		citylist,
		hospitalList,
		hospitalList2,
		addAppointment,
		updateAppointment,
		addRecord,
		updateRecord,
		RecordList
	} from "@/api/system/user"
	export default {
		data() {
			return {
				disabled: false,
				imageValue: [],
				// 单选数据源
				keshiTree: [],
				msgType: 'success',
				hospitalTree: [],
				medicalTreatment: [{
					text: '是',
					value: 0
				}, {
					text: '否',
					value: 1
				}],
				configParams: {
					labelKey: "dictLabel",
					valueKey: "dictValue",
				},
				dataTree: [

				],
				IDType: [],
				formData: {
					"createBy": null,
					"createTime": null,
					"updateBy": null,
					"updateTime": null,
					"remark": null,
					"activationCode": "",
					"exclusiveRightsName": "",
					"exclusiveRightsId": '',
					"patientName": "",
					"idType": "",
					"idNumber": "",
					"contactNumber": "",
					"backupNumber": "",
					"insuranceCardNumber": "",
					"outOfTown": null,
					"hospitalCity": "",
					"hospitalName": "",
					"departmentName": "",
					"expectedTime": "",
					"medicalRecords": null,
					"hospitalizationOrder": null,
					"notes": null
				},
				Timer: "",
				option: {},
				shengyu: 0,
				selectedImg:"",
				rules: {
					// 对name字段进行必填验证
					name: {
						rules: [{
								required: true,
								errorMessage: '请输入姓名',
							},
							// {
							// 	minLength: 3,
							// 	maxLength: 5,
							// 	errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符',
							// }
						]
					},
					idType: {
						rules: [{
							required: true,
							errorMessage: '请选择证件类型',
						}]
					},
					idNumber: {
						rules: [{
							required: true,
							errorMessage: '请输入证件号码',
						}]
					},
					phoneNumber: {
						rules: [{
							required: true,
							errorMessage: '请输入手机号',
						}]
					},
					// city: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请选择所在城市',
					// 	}]
					// }
				},
				currentItem: {}
			}
		},
		onLoad: function(option) {
			this.option = option
			this.disabled = JSON.parse(this.option.disabled)
			this.currentItem = JSON.parse(option.currentItem)
			console.log(option, 'option')
			this.getData()
			this.formData.patientName = this.currentItem.username
			this.formData.idType = this.currentItem.cardType
			this.formData.idNumber = this.currentItem.idNumber
			this.formData.contactNumber = this.currentItem.phoneNumber
			this.getprovincelist()
		},
		methods: {
			maskClick(e) {
				console.log('maskClick事件:', e);
			},
			getprovincelist() {
				provincelist().then(res => {
					console.log(res, 'res')
					this.dataTree = this.formatData(res.rows, 0)
					console.log(this.dataTree, 'this.dataTree')
				})
			},
			dialogConfirm2() {
				this.$refs.messages.close()
				uni.navigateTo({
					url: `/pages/code/serviceIntroduct`
				});
			},
			dialogClose2() {
				this.$refs.messages.close()
			},
			onnodeclick(val) {
				console.log(val, '额我问问');
				console.log(val,'额我问问');
				let data = ['北京市','上海市','天津市','重庆市']
				console.log(data.indexOf(val.name))
				if(data.indexOf(val.name)<=-1 && val.level < 2){
					citylist(val.id).then(res => {
						console.log(res, 'res')
						this.dataTree.forEach(item =>{
							if(item.id == val.id){
								item.children = this.formatData(res.rows, 1)
							}
						})
					})
				} else {
					console.log(data)
				}
				//请求医院的接口  level 1 第一层 查省  level 2 第二层 查市
				let dat = val.name.substr(0, val.name.length - 1);
				console.log(dat, 'dat')
				val.level == 1 ? this.hospitalList(dat) : this.hospitalList2(dat)
			},
			hospitalList(data) {
				hospitalList(data).then(res => {
					this.hospitalTree = []
					console.log(res, 'res')
					res.rows.forEach(item => {
						this.hospitalTree.push({
							text: item.hospitalname,
							value: item.hospitalname,
						})
					})
				})
			},
			// 获取上传状态
			select(e) {
				this.upload(e)
			},
			upload(e) {
				const tempFilePaths = e.tempFilePaths;
				uni.uploadFile({
					url: 'http://localhost:1024/dev-api/common/upload',
					//你的上传文件的接口地址：若依的一般就是这个
					filePath: tempFilePaths[0],
					header:{
						"authorization":getToken()
					},
					name: 'file',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						// console.log(uploadFileRes.data);
						const imgUrls = JSON.parse(uploadFileRes.data).url;
						this.selectedImg = this.selectedImg + imgUrls + ',';
						this.formData.hospitalizationOrder = this.selectedImg
						//this.selectedImg是我定义的获取文件的属性，每个用逗号隔开。
						console.log(this.selectedImg);
					}
				});

			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功')
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			hospitalList2(data) {
				hospitalList2(data).then(res => {
					this.hospitalTree = []
					console.log(res, 'res')
					res.rows.forEach(item => {
						this.hospitalTree.push({
							text: item.hospitalname,
							value: item.hospitalname,
						})
					})
				})
			},
			formatData(data, level) {
				level = level + 1
				let result = []
				if (!data.length) return []
				result = data.map((item, index) => {
					let obj = {
						...item,
						text: item.name,
						value: item.id, // 仅仅用于唯一标识数据作用的,解决value值重复问题
						level: level, // 标识当前属于第几个层级
						children: item.children && item.children.length > 0 ? formatData(item.children,
							level) : []
					}
					return obj
				})
				return result
			},
			getData() {
				document_type().then(res => {
					console.log(res, 'res')
					this.IDType = res.data
				})
			},
			//更新状态
			updata() {
				//获取当前年月日
				var now = new Date();
				var year = now.getFullYear(); //得到年份
				var month = now.getMonth() + 1; //得到月份
				var date = now.getDate(); //得到日期
				var data = year + "-" + month + "-" + date + "-";
				let form = {}
				form.usageCount = Number(this.currentItem.Number) - 1
				form.beneficiaryName = this.formData.patientName
				form.beneficiaryPhone = this.formData.contactNumber
				form.activationCode = this.formData.activationCode
				form.exclusiveBenefitId = this.formData.exclusiveRightsId
				form.exclusiveBenefitName = this.formData.exclusiveRightsName
				this.shengyu = form.usageCount
				addRecord(form).then(res => {
					if (res.code == 200) {
						this.$refs.messages.open()
						console.log(res, 'res')
					}
				})
			},
			sendBtnautograph() {
				//需要将次数和订单都保存
				// 订单信息中需要有激活码、专属权益名称、专属权益id
				console.log(this.currentItem, 'this.currentItem')
				this.formData.exclusiveRightsName = this.currentItem.title
				this.formData.exclusiveRightsId = this.currentItem.exclusiveRightsID
				this.formData.activationCode = this.currentItem.activationCode
				this.formData.expectedTime = this.formData.expectedTime.toString()
				console.log(this.formData, 'this.formData')
				this.$refs.form.validate().then(res => {
					console.log('表单数据信息：', res);
					addAppointment(this.formData).then(res => {
						if (res.code == 200) {
							RecordList(this.formData.activationCode, this.formData.exclusiveRightsId).then(
								red => {
									if (red?.rows.length == 0) {
										this.updata()
									} else {
										// 拿到当前数据进行number - 1
										let data = red?.rows[0]
										data.usageCount = data.usageCount - 1
										this.shengyu = data.usageCount
										updateRecord(data).then(res => {
											this.$refs.messages.open()
										})
									}
								})
						}
					})
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			onpopupopened(e) {
				console.log('popupopened', e);
			},
			onpopupclosed(e) {
				console.log('popupclosed');
			},
			onchange(e) {
				console.log('onchange:', e);
			}
		}
	}
</script>

<style>
	.plainlk1 {
		border-color: transparent;
		background: rgb(41, 197, 136);
		color: rgb(255, 255, 255);
	}

	.plainlk {
		border-color: rgb(41, 197, 136);
		color: rgb(41, 197, 136);
	}

	.Applyappointment .uni-easyinput__content-input .uni-input-input {
		text-align: right;
	}

	.Applyappointment {
		width: 100%;
		height: 100vh;
		background: #fff;
		padding: 20rpx;
	}

	.Applyappointment .hdsIGN {
		background: rgb(255, 255, 255);
		font-size: 1rem;
		padding: 0px 1.2rem;
	}

	.Applyappointment .hdsIGN>h3::before {
		content: "";
		position: absolute;
		background: rgb(18, 205, 159);
		width: 0.2222em;
		height: calc(100% - 2.1667em);
		top: 1.1em;
		left: -0.6667em;
	}

	.Applyappointment .hdsIGN>h3 {
		margin: 0px;
		font-size: 38rpx;
		padding: 0.8333em 0px;
		position: relative;
		color: rgba(0, 0, 0, 0.8);
	}

	.Applyappointment h3 {
		font-size: 38rpx;
		font-weight: bold;
	}
</style>

<style>
	.uni-forms-item__label {
		width: 82px !important;
	}
</style>